﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using SilverLightApp.DataHelperService;
using System.Windows.Browser;

namespace SilverLightApp
{
  public partial class CauseProgression : Page
  {
    public string country = "NA";
    public string cause = "NA";
    public delegate void SetRectangle(object stat, double height);
    public DataHelperClient dataHelperClient = new DataHelperClient();
    public Int32 maxCount = 0;
    public delegate void UpdateCause();
    HtmlDocument doc = null;
    int chosenYear = -1;
    
    public CauseProgression()
    {
      InitializeComponent();
      dataHelperClient.GetMaxValueForCauseCompleted += new EventHandler<GetMaxValueForCauseCompletedEventArgs>(dataHelperClient_GetMaxValueForCauseCompleted);
      dataHelperClient.GetCauseProgressionCompleted += new EventHandler<GetCauseProgressionCompletedEventArgs>(dataHelperClient_GetCauseProgressionCompleted);
      //dataHelperClient.GetMaxValueForCauseAsync(country, cause);
      doc = HtmlPage.Document;
      HtmlElement countryName = doc.GetElementById("countryName");
      country = countryName.GetAttribute("value");
      if (String.IsNullOrWhiteSpace(country))
      {
        //MessageBox.Show("Please select a country first");
        return;
      }
      System.Threading.Thread updaterThread = new System.Threading.Thread(GetChosenCause);
      updaterThread.Start();
    }

    public void Update()
    {
      HtmlElement newChosenCause = doc.GetElementById("chosenCause");
      HtmlElement newSliderValue = doc.GetElementById("sliderValue");
      int newChosenYear = int.Parse(newSliderValue.GetAttribute("value"));
      if (newChosenYear != chosenYear && newChosenYear != -1)
      {
        chosenYear = newChosenYear;
        UpdateGraphYear(chosenYear);
      }
      string newCause = newChosenCause.GetAttribute("value");
      if (newCause == cause || newCause == "NA")
        return;
      else
      {
        cause = newCause;
        tbChosenCause.Text = "Cause: " + cause.Trim();
        dataHelperClient.GetMaxValueForCauseAsync(country, cause);
      }
    }

    public void GetChosenCause()
    {
      UpdateCause updateCause = new UpdateCause(Update);
      while (true)
      {
        this.Dispatcher.BeginInvoke(updateCause);
        System.Threading.Thread.Sleep(500);
      }
    }

    void dataHelperClient_GetMaxValueForCauseCompleted(object sender, GetMaxValueForCauseCompletedEventArgs e)
    {
      maxCount = e.Result;
      PopulateYAxis();
      dataHelperClient.GetCauseProgressionAsync(country, cause);
    }

    private void PopulateYAxis()
    {
      string elementName = "tbCount{0}";
      Int32 jump = maxCount / 5;
      int powerOf10 = (int)Math.Log10(maxCount) - 1;
      for (int i = 1; i <= 5; i++)
      {
        int multiplier = 0;
        TextBlock block = (TextBlock)LayoutRoot.FindName(String.Format(elementName, i));
        multiplier = (int)((jump * i) / Math.Pow(10, powerOf10));
        block.Text = (multiplier * Math.Pow(10, powerOf10)).ToString();
      }
    }

    void dataHelperClient_GetCauseProgressionCompleted(object sender, GetCauseProgressionCompletedEventArgs e)
    {
      ClearOldData();
      SetupXAxis(e);
      UpdateGraph(e);
    }

    private void ClearOldData()
    {
      List<Rectangle> rectanglesToRemove = new List<Rectangle>();
      Rectangle rect = null;
      for (int i = 0; i < LayoutRoot.Children.Count; i++)
      {
        if (LayoutRoot.Children[i].ToString() == "System.Windows.Shapes.Rectangle")
        {
          rect = (Rectangle)LayoutRoot.Children[i];
          if (rect.Name.Contains("rectProgression"))
          {
            rectanglesToRemove.Add(rect);
          }
        }   
      }
      foreach (Rectangle rectangleToRemove in rectanglesToRemove)
      {
        LayoutRoot.Children.Remove(rectangleToRemove);
      }
    }

    private void UpdateGraphYear(int chosenYear)
    {
      Rectangle rect = null;
      for (int i = 0; i < LayoutRoot.Children.Count; i++)
      {
        if (LayoutRoot.Children[i].ToString() == "System.Windows.Shapes.Rectangle")
        {
          rect = (Rectangle)LayoutRoot.Children[i];
          if (rect.Name.Contains("rectProgression" + chosenYear.ToString()))
          {
            rect.Fill = new SolidColorBrush { Color = Color.FromArgb(255, 2, 105, 255) };
          }
          else
            rect.Fill = new SolidColorBrush { Color = Color.FromArgb(255, 188, 2, 2) };
        }
      }
    }

    private void UpdateGraph(GetCauseProgressionCompletedEventArgs e)
    {
      double factor = (double)360 / maxCount;
      int range = (int)xAxis.Width;
      int spacing = range / (e.Result.Count);
      int fromLeft = 100;
      int width = 30;
      double height = 0;
      for (int i = 0; i < e.Result.Count; i++)
      {
        Rectangle rect = null;
        height = e.Result[i].Count * factor;
        rect = new Rectangle() { Stroke = new SolidColorBrush(Colors.Black), Name = "rectProgression" + e.Result[i].Year, Width = width, Height = height, Fill = new SolidColorBrush { Color = Color.FromArgb(255, 188, 2, 2) } };
        rect.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
        this.LayoutRoot.Children.Add(rect);
        Canvas.SetLeft(rect, fromLeft + spacing * i);
        Canvas.SetTop(rect, 527 - height);
        if(chosenYear == -1)
          UpdateGraphYear(int.Parse(e.Result[0].Year));
        else
          UpdateGraphYear(chosenYear);
      }
    }

    private void SetupXAxis(GetCauseProgressionCompletedEventArgs e)
    {
      int range = (int)xAxis.Width;
      int spacing = range / (e.Result.Count);
      int fromLeft = 100;
      int width = 20;
      int height = 23;
      int fromTop = 530;
      for (int i = 0; i < e.Result.Count; i++)
      {
        TextBlock tb = new TextBlock() { Width = width, Height = height };
        tb.Text = e.Result[i].Year.ToString();
        this.LayoutRoot.Children.Add(tb);
        Canvas.SetLeft(tb, fromLeft + spacing * i);
        Canvas.SetTop(tb, fromTop);
      }
    }

    // Executes when the user navigates to this page.
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
    }

  }
}
